import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import requests
import json
import os

class PromptGeneratorApp:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("智能提示词生成器")
        self.root.geometry("800x600")
        
        # 通义API配置
        self.api_key = os.getenv("DASHSCOPE_API_KEY", "your-api-key-here")
        self.api_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
        
        # GUI组件初始化
        self.create_widgets()
        self.load_history()
        
    def create_widgets(self):
        # 输入区域
        input_frame = ttk.LabelFrame(self.root, text="需求描述")
        input_frame.pack(pady=10, padx=10, fill="x")
        
        self.input_text = scrolledtext.ScrolledText(input_frame, height=5)
        self.input_text.pack(fill="x", padx=5, pady=5)
        
        # 生成按钮
        ttk.Button(input_frame, text="生成提示词", command=self.generate_prompts).pack(pady=5)

        # 候选提示词区域
        candidates_frame = ttk.LabelFrame(self.root, text="候选提示词（双击选择）")
        candidates_frame.pack(pady=10, padx=10, fill="both", expand=True)
        
        self.candidate_list = tk.Listbox(candidates_frame)
        self.candidate_list.pack(fill="both", expand=True, padx=5, pady=5)
        self.candidate_list.bind("<Double-Button-1>", self.select_prompt)

        # 历史记录
        history_frame = ttk.LabelFrame(self.root, text="历史记录")
        history_frame.pack(pady=10, padx=10, fill="x")
        
        self.history_list = tk.Listbox(history_frame, height=6)
        self.history_list.pack(fill="x", padx=5, pady=5)

    def generate_prompts(self):
        user_input = self.input_text.get("1.0", tk.END).strip()
        if not user_input:
            messagebox.showwarning("警告", "请输入需求描述")
            return
            
        try:
            headers = {
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            }
            
            payload = {
                "model": "qwen-max",
                "input": {
                    "messages": [
                        {
                            "role": "system",
                            "content": "你是一个专业的提示词工程师，请根据用户需求生成5个不同风格的优质提示词，用编号列表形式返回"
                        },
                        {
                            "role": "user",
                            "content": user_input
                        }
                    ]
                }
            }
            
            response = requests.post(self.api_url, json=payload, headers=headers)
            response.raise_for_status()
            
            # 解析响应
            choices = response.json()["output"]["choices"]
            self.display_results(choices[0]["message"]["content"])
            
        except Exception as e:
            messagebox.showerror("错误", f"生成失败: {str(e)}")

    def display_results(self, content):
        self.candidate_list.delete(0, tk.END)
        prompts = [line.split(". ", 1)[1] for line in content.split("\n") if line.strip()]
        for prompt in prompts:
            self.candidate_list.insert(tk.END, prompt)

    def select_prompt(self, event):
        selection = self.candidate_list.curselection()
        if selection:
            selected = self.candidate_list.get(selection[0])
            self.history_list.insert(tk.END, selected)
            self.save_to_history(selected)

    def save_to_history(self, prompt):
        with open("prompt_history.json", "a") as f:
            f.write(json.dumps({"prompt": prompt}) + "\n")

    def load_history(self):
        try:
            with open("prompt_history.json", "r") as f:
                for line in f:
                    data = json.loads(line)
                    self.history_list.insert(tk.END, data["prompt"])
        except FileNotFoundError:
            pass

if __name__ == "__main__":
    app = PromptGeneratorApp()
    app.root.mainloop()